<template>
  <div class="app-container">
    <!-- 对话框(添加 / 修改) -->
    <el-dialog :title="dialogTitle" :visible.sync="dialogVisible" width="800px" v-dialogDrag append-to-body>
      <el-form ref="formRef" :model="formData" :rules="formRules" v-loading="formLoading" label-width="120px">
        <el-row :gutter="20" >
          <el-col :span="12">
            <el-form-item label="仓库" prop="warehouseId">
              <treeselect
                v-model="formData.warehouseId"
                :options="warehouseTree"
                :normalizer="normalizerW"
                placeholder="选择仓库"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="库位编码" prop="storageLocationCode">
              <el-input v-model="formData.storageLocationCode" placeholder="请输入库位编码" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20" >
          <el-col :span="12">
            <el-form-item label="库位名称" prop="storageLocationName">
              <el-input v-model="formData.storageLocationName" placeholder="请输入库位名称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="库位类型" prop="storageLocationType">
              <el-select v-model="formData.storageLocationType" filterable style="width: 100%" placeholder="请选择库位类型">
                <el-option v-for="dict in this.getDictDatas(DICT_TYPE.STORAGE_LOCATION_TYPE)" :key="dict.value" :label="dict.label" :value="parseInt(dict.value)"/>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm" :disabled="formLoading">确 定</el-button>
        <el-button @click="dialogVisible = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import * as LocationApi from '@/api/storage/location';
import { getDictDatas,getDictDataLabel, DICT_TYPE } from '@/utils/dict'
import Treeselect from '@riophae/vue-treeselect';
import '@riophae/vue-treeselect/dist/vue-treeselect.css';
import * as WarehouseApi from '@/api/storage/warehouse';

export default {
  name: "LocationForm",
  components: {
    Treeselect
  },
  props: {
    warehouseId: {
      type: [Number, String],
      default: null
    }
  },
  data() {
    return {
      // 弹出层标题
      dialogTitle: "",
      // 是否显示弹出层
      dialogVisible: false,
      // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
      formLoading: false,
      // 表单参数
      formData: {
        id: undefined,
        warehouseId: undefined,
        storageLocationCode: undefined,
        storageLocationName: undefined,
        storageLocationType: undefined,
      },
      // 表单校验
      formRules: {
        warehouseId: [{ required: true, message: '仓库不能为空', trigger: 'blur' }],
      },
      // 仓库树数据
      warehouseTree: []
    };
  },
  methods: {
    /** 打开弹窗 */
    async open(id) {
      this.dialogVisible = true;
      this.reset();

      // 加载仓库树数据
      await this.getWarehouseTree();

      // 如果有传入的仓库ID，设置到表单中
      if (this.warehouseId) {
        this.formData.warehouseId = this.warehouseId;
      }

      // 修改时，设置数据
      if (id) {
        this.formLoading = true;
        try {
          const res = await LocationApi.getLocation(id);
          this.formData = res.data;
          this.dialogTitle = "编辑仓储仓库库位";
        } finally {
          this.formLoading = false;
        }
      } else {
        this.dialogTitle = "新增仓储仓库库位";
      }
    },

    /** 获取仓库树数据 */
    async getWarehouseTree() {
      try {
        const params = {
          pageNo: 1,
          pageSize: 1000 // 获取足够多的数据用于构建树
        };
        const res = await WarehouseApi.getWarehousePage(params);
        // 处理树结构，确保有正确的格式
        const processedTree = res.data;

        this.warehouseTree = processedTree;
      } catch (error) {
        console.error('获取仓库树数据失败:', error);
        this.$modal.msgError('获取仓库树数据失败');
      }
    },

    /** 树节点标准化处理 */
    normalizerW(node) {
      const normalizedNode = {
        id: node.id,
        label: node.warehouseName,
        // 只有当children存在且不为空数组时才传递children属性
        // 这样没有子节点的节点就不会显示展开按钮
        children: node.children && node.children.length > 0 ? node.children : undefined
      };
      return normalizedNode;
    },

    /** 处理树结构数据 */


      // 递归构建子节点


    /** 提交按钮 */
    async submitForm() {
      // 校验主表
      await this.$refs["formRef"].validate();
      this.formLoading = true;
      try {
        const data = this.formData;
        // 修改的提交
        if (data.id) {
          await LocationApi.updateLocation(data);
          this.$modal.msgSuccess("修改成功");
          this.dialogVisible = false;
          this.$emit('success');
          return;
        }
        // 添加的提交
        await LocationApi.createLocation(data);
        this.$modal.msgSuccess("新增成功");
        this.dialogVisible = false;
        this.$emit('success');
      } finally {
        this.formLoading = false;
      }
    },
    /** 表单重置 */
    reset() {
      this.formData = {
        id: undefined,
        warehouseId: undefined,
        storageLocationCode: undefined,
        storageLocationName: undefined,
        storageLocationType: undefined,

      };
      this.resetForm("formRef");
    }
  }
};
</script>
